//
//  DriverViewController.swift
//  iOS-RxSwift-Tutorials_Example
//
//  Created by mengru.tian on 2020/9/18.
//  Copyright © 2020 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift

class DriverViewController: UIViewController {

    @IBOutlet weak var responseL: UILabel!
    @IBOutlet weak var textfield: UITextField!
    private let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "16.特征序列2：Driver"
        view.backgroundColor = .white
        
        // testDriver1()
        testDriver2()
    }
    
    // 模拟查询数据
    func dealwithData(inputText:String)-> Observable<String>{
        print("请求网络了 \(Thread.current)") // data
        return Observable<String>.create({ (ob) -> Disposable in
            if inputText == "1234" {
                ob.onError(NSError.init(domain: "com.lgcooci.cn", code: 10086, userInfo: nil))
            }

            DispatchQueue.global().async {
                ob.onNext("已经输入:\(inputText)")
                ob.onCompleted()
            }
            return Disposables.create()
        })
    }
    
    // 使用传统方式
    func testDriver1() {
        let result = textfield.rx.text.skip(1).flatMap { [weak self](input) -> Observable<String> in
             return (self?.dealwithData(inputText: input ?? ""))!
                .observeOn(MainScheduler.instance)// 必须在主线程
        }
        .share(replay: 1, scope: .whileConnected)// 请求多次网络解决办法
        .catchErrorJustReturn("检测到了错误事件")
        // 第一次订阅
        result.subscribe { (even) in
            print(even)
            print(Thread.current)
        }.disposed(by: disposeBag)
        
        // 第二次订阅
        result.subscribe { (even) in
            print(even)
            print(Thread.current)
        }.disposed(by: disposeBag)
        
        result.bind(to: responseL.rx.text).disposed(by: disposeBag)
    }
    
    // 使用Driver
    func testDriver2() {
        let result = textfield.rx.text.orEmpty
        .asDriver()
        .flatMap {  return self.dealwithData(inputText: $0)
        .asDriver(onErrorJustReturn: "检测到了错误事件") }
        
        // 第一次订阅
        result.map{ "\( $0 )" }
        .drive(self.responseL.rx.text)
        .disposed(by: disposeBag)
    }

}
